import './index.css';
import React, { useState, useEffect, useContext } from 'react';
import {
    UserOutlined, GlobalOutlined
} from '@ant-design/icons';
import {
    Card, Row, Col, Form, Descriptions, Tag, Button, Select, Radio, Divider, Avatar, message
} from 'antd';
import ThemeContext from '@/theme/ThemeContext';
import { useTranslation } from 'react-i18next';
import { useLanguage } from '../../contexts/LanguageContext';
import MainLayout from '../../components/MainLayout';
import withAuth from '../../components/WithAuth';

const SystemSettings = () => {
    const [form] = Form.useForm();
    const { t } = useTranslation();
    const { language, changeLanguage } = useLanguage();
    const { theme, setTheme } = useContext(ThemeContext);
    const [userName, setUserName] = useState('');
    const [privilegeLevelText, setPrivilegeLevelText] = useState('');

    useEffect(() => {
        const storedUserName = localStorage.getItem('username');
        if (storedUserName !== userName) {
            setUserName(storedUserName);
        }
    }, [localStorage.getItem('username')]);

    const languageOptions = [
        { value: 'zh-CN', label: '简体中文' },
        { value: 'en-US', label: 'English' },
    ];

    const themeOptions = [
        { value: 'light', label: t('浅色模式') },
        { value: 'dark', label: t('深色模式') },
    ];

    const handleSaveSettings = () => {
        const values = form.getFieldsValue();

        const settingsToSave = {
            language: values.language
        };

        localStorage.setItem('userSettings', JSON.stringify(settingsToSave));
        changeLanguage(values.language);
        setTheme(values.theme); 
        message.success(t('设置成功'));
        setTimeout(() => {
            window.location.reload();
        }, 1000);
    };
    useEffect(() => {
        const savedSettings = localStorage.getItem('userSettings');
        if (savedSettings) {
            const settings = JSON.parse(savedSettings);
            form.setFieldsValue({
                language: settings.language,
                theme: theme 
            });
        } else {
            form.setFieldsValue({
                theme: theme,
                language: language
            });
        }
    }, [theme, language]); 

    useEffect(() => {
        const privilegeLevel = localStorage.getItem('privilege_level');
        if (privilegeLevel === '1') {
            setPrivilegeLevelText(t('管理员'));
        } else if (privilegeLevel === '0') {
            setPrivilegeLevelText(t('普通用户'));
        } else {
            setPrivilegeLevelText('未知权限等级');
        }
    }, []);

    return (
        <MainLayout defaultSelectedKey="6">
            <Row gutter={[16, 16]}>
                <Col xs={24} md={24}>
                    <Card title={t("个人信息")}>
                        <div style={{ textAlign: 'center', marginBottom: 16 }}>
                            <Avatar
                                size={64}
                                icon={<UserOutlined />}
                                style={{ backgroundColor: '#1677ff' }}
                            />
                        </div>
                        <Descriptions column={1}>
                            <Descriptions.Item label={t("用户名")}>
                                {userName}
                            </Descriptions.Item>
                            <Descriptions.Item label={t("权限级别")}>
                                <Tag color="gold">{privilegeLevelText}</Tag>
                            </Descriptions.Item>
                        </Descriptions>
                    </Card>
                </Col>
            </Row>
            <Row gutter={[16, 16]} style={{ marginTop: "30px" }}>
                <Col xs={24} md={24}>
                    <Card title={t("系统设置")}>
                        <Form form={form}>
                            <Form.Item
                                label={t('主题颜色')}
                                name="theme"
                            >
                                <Radio.Group
                                    options={themeOptions}
                                    optionType="button"
                                    buttonStyle="solid"
                                    onChange={({ target: { value } }) => {
                                        setTheme(value);
                                    }}
                                />
                            </Form.Item>

                            <Divider />

                            <Form.Item
                                label={t("系统语言")}
                                name="language"
                            >
                                <Select
                                    style={{ width: "25%" }}
                                    suffixIcon={<GlobalOutlined />}
                                    onChange={(value) => form.setFieldsValue({ language: value })}
                                >
                                    {languageOptions.map(option => (
                                        <Select.Option
                                            key={option.value}
                                            value={option.value}
                                        >
                                            {option.label}
                                        </Select.Option>
                                    ))}
                                </Select>
                            </Form.Item>
                            <Divider />
                            <Form.Item>
                                <Button
                                    type="primary"
                                    className='shezhibutton'
                                    onClick={handleSaveSettings}
                                >
                                    {t("保存设置")}
                                </Button>
                            </Form.Item>
                        </Form>
                    </Card>
                </Col>
            </Row>
        </MainLayout>
    );
};

export default withAuth(SystemSettings);